import React, { useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useIphoneX } from "./use-iphonex";

export type BlockOptions = {
  className?: string;
  styles?: React.CSSProperties;
};

export type FooterProps = {
  /** 创建底部占位块的容器 默认body */
  container?: Element;
  /** 是否展示底部占位块/配置选项 */
  block?: boolean | BlockOptions;
  children: React.ReactNode;
  className?: string;
  styles?: React.CSSProperties;
};

export const Footer = ({
  styles = {},
  className = "",
  container = document.body,
  block = false,
  children,
}: FooterProps) => {
  const [isIphonex] = useIphoneX();
  const footerRef = useRef(null);
  const [height, setHeight] = useState(0);

  useLayoutEffect(() => {
    setHeight(
      (footerRef.current as unknown as Element)?.getBoundingClientRect()?.height
    );
  }, [children]);

  const blockOptions = block as BlockOptions;

  return (
    <>
      {block
        ? createPortal(
            <div
              className={blockOptions?.className || ""}
              style={{
                width: "100vw",
                height: `${height}px`,
                ...(blockOptions?.styles || {}),
              }}
            ></div>,
            container
          )
        : null}
      <div
        className={className}
        style={{
          position: "fixed",
          bottom: 0,
          left: 0,
          width: "100vw",
          paddingBottom: isIphonex ? `${34}px` : 0,
          ...styles,
        }}
        ref={footerRef}
      >
        {children}
      </div>
    </>
  );
};
